package com.weapp.system.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.weapp.common.RestResponse;
import com.weapp.common.utils.JWTUtil;
import com.weapp.common.utils.RedisUtils;
import com.weapp.system.constant.CacheConstants;
import com.weapp.system.entity.User;
import com.weapp.system.qo.LoginRequest;
import com.weapp.system.service.impl.UserServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author jsy
 * @description: 用户相关接口
 * @date 2022/7/13 15:36
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/wx/user")
public class WxUserController {

  private final Logger log = LoggerFactory.getLogger(WxUserController.class);

  @Autowired
  private UserServiceImpl userService;

  @Autowired
  private RedisUtils redisUtils;

  @Autowired
  private WxMaService wxService;

  @ApiOperation(value = "用户登陆", tags = "用户登陆")
  @RequestMapping(value = "/login", method = RequestMethod.POST)
  public RestResponse<Object> login(LoginRequest loginRequest) {
    try {
      WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(loginRequest.getCode());
      log.info(session.getSessionKey());
      log.info(session.getOpenid());
      User user = userService.selectByOpenId(session.getOpenid());
      if (user == null) {
        //todo 注册相关业务
        return RestResponse.builder().data("").build();
      } else {
        String userId = user.getId().toString();
        redisUtils.set(CacheConstants.LOGIN_TOKEN_KEY + userId, user,30L, TimeUnit.MINUTES);
        String jwtToken = JWTUtil.generateJWT(userId);
        JSONObject data = JSONUtil.createObj()
          .set("userId", userId)
          .set("token", jwtToken);
        return RestResponse.builder().data(data).build();
      }
    } catch (WxErrorException e) {
      log.error(e.getMessage(), e);
      return RestResponse.builder().message("登陆异常,请联系服务人员!").build();
    } finally {
      //清理ThreadLocal
      WxMaConfigHolder.remove();
    }
  }
}
